import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.ArrayList;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created by ospip on 2017/11/28.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class BroadcastThread extends Thread {
    private String multiCastIP = "224.116.8.1";
    private int ttl = 1;
    private MulticastSocket msocket;
    private DatagramPacket pack;
    private InetAddress group;
    private int port = 817;
    private String message = "";
    private byte[] buf;
    private ArrayList<UserQueue> list;
    private int interval;

    public BroadcastThread(ArrayList<UserQueue> list, int interval) {
        System.out.println("Start broadcasting...");
        this.list = list;
        this.interval = interval;

        try {
            group = InetAddress.getByName(multiCastIP);
            msocket = new MulticastSocket(port);
            msocket.setTimeToLive(ttl);
            msocket.joinGroup(group);
        }
        catch (Exception e) {
            System.out.println("Broadcast Error: " + e.getMessage());
        }
    }

    public BroadcastThread(ArrayList<UserQueue> list) {this(list, 5000);}

    @Override
    public void run() {
        while(true) {
            message = "";
            for (UserQueue i : list) {
                message += i.getComment() + "," + i.getSize() + "|";
            }

            try {
                message += InetAddress.getLocalHost().getHostAddress();
                //System.out.println(message);
                buf = message.getBytes();
                pack = new DatagramPacket(buf, buf.length, group, port);
                msocket.send(pack);
                Thread.sleep(interval);
            }
            catch (Exception e) {}
        }
    }

    public static void main(String[] args) {
        ArrayList<UserQueue> q = new ArrayList<>();
        q.add(new UserQueue(q.size(),"业务1"));
        q.add(new UserQueue(q.size(), "业务2"));
        q.get(0).insert();
        new BroadcastThread(q).start();
    }
}
